package com.inossem.utils.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created by leij on 2017/9/2.
 */

public class RootUtils {

    /**
     * 判断手机是否破解
     * @author leij
     * @return true （破解） false （未破解）
     */
    public static boolean isRoot() {
        if (checkRootMethod1()){return true;}
        if (checkRootMethod2()){return true;}
        if (checkRootMethod3()){return true;}
        return false;
    }

    private static boolean checkRootMethod1(){
        String buildTags = android.os.Build.TAGS;
        if (buildTags != null && buildTags.contains("test-keys")) {
            return true;
        }
        return false;
    }

    private static boolean checkRootMethod2(){
        try {
            File file = new File("/system/app/Superuser.apk");
            if (file.exists()) {
                return true;
            }
        } catch (Exception e) { }

        return false;
    }

    private static boolean checkRootMethod3() {
        if (ExecShell.executeCommand(ExecShell.SHELL_CMD.check_su_binary) != null){
            return true;
        }else{
            return false;
        }
    }

    private static class ExecShell {

        public static enum SHELL_CMD {
            check_su_binary(new String[] {"/system/xbin/which","su"});
            String[] command;
            SHELL_CMD(String[] command){
                this.command = command;
            }
        }

        public static ArrayList<String> executeCommand(SHELL_CMD shellCmd){
            String line = null;
            ArrayList<String> fullResponse = new ArrayList<String>();
            Process localProcess = null;
            try {
                localProcess = Runtime.getRuntime().exec(shellCmd.command);
            } catch (Exception e) {
                return null;
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
            try {
                while ((line = in.readLine()) != null) {
                    fullResponse.add(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return fullResponse;
        }

    }

}
